import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import jdk.internal.jfr.events.FileWriteEvent;

public class RestConnection {

	/**
	 * @param args
	 */
	// public static void main(String[] args) throws Exception {
	//
	// URL url = new URL(
	// "http://www.google.it");
	// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	// int status = conn.getResponseCode();
	// System.out.println("RESPONSE CODE: " + status);
	// System.out.println("CONTENT TYPE: " + conn.getContentType());
	// if (status >= 200 && status <= 299) {
	// InputStreamReader in = new InputStreamReader(conn.getInputStream(),
	// "UTF-8");
	// int c;
	// while ((c = in.read()) != -1)
	// System.out.print((char) c);
	// in.close();
	// }
	//
	// }

	public static String encodeForm(Map<String, String> data) {
		StringBuffer sb = new StringBuffer();
		try {
			for (String key : data.keySet()) {
				sb.append(URLEncoder.encode(key, "UTF-8"));
				sb.append('=');
				sb.append(URLEncoder.encode(data.get(key), "UTF-8"));
				sb.append('&');
			}
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("Unsupported encoding UTF-8");
		}
		return sb.toString();
	}

	public static void main(String args[]) throws Exception {
		URL url = new URL("http://www.amazon.it/s/ref=nb_sb_noss?__mk_it_IT=%C3%85M%C3%85%C5%BD%C3%95%C3%91&url=search-alias%3Daps");
		Map<String, String> form = new HashMap<String, String>();
		form.put("field-keywords", "arduino");
		File output = new File("C:\\Users\\RaF\\Desktop\\provaREST.html");
		FileWriter file = new FileWriter(output);
		String body = encodeForm(form);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("POST");
		conn.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded; charset=UTF-8");
		conn.setDoOutput(true);
		PrintWriter pw = new PrintWriter(new OutputStreamWriter(
				conn.getOutputStream(), "UTF-8"));
		pw.print(body);
		pw.close();
		int status = conn.getResponseCode();
		System.out.println("RESPONSE CODE: " + status);
		System.out.println("CONTENT TYPE: " + conn.getContentType());
		if (status >= 200 && status <= 299) {
			InputStreamReader in = new InputStreamReader(conn.getInputStream(),
					"UTF-8");
			int c;
			while ((c = in.read()) != -1)
				file.append((char) c);
			in.close();
		}
	}
}
